import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/index.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";

import "api.dart";

class Residents extends StatefulWidget {
  const Residents({super.key});

  @override
  ResidentsState createState() => ResidentsState();
}

class ResidentsState extends State<Residents> {
  final ScrollController _scrollController = ScrollController();
  List _residents = [];
  bool _isLoading = false;
  Map<String, dynamic> _params = {"pageSize": 20, "pageNum": 1, "status": ""};
  List<Map<String, dynamic>> _status = [{
    "label": "全部",
    "value": ""
  }, {
    "label": "入住中",
    "value": "1"
  }, {
    "label": "已退房",
    "value": "2"
  }];
  int _total = 0;
  // {
  // "renterList": [{ "name": "测试"}],
  // "checkInStart": "2021-03-03 13:23",
  // "checkInEnd": "2025-03-03 13:23",
  // "room": {"name": "A102", "buildingName": "公寓"},
  // }

  Future<void> _getResidents() async {
    try {
      _isLoading = true;
      Map resData = await residentsApi.getResidents(_params);
      _isLoading = false;
      setState(() {
        _total = resData["total"] ?? 0;
        _residents = resData["rows"] ?? [];
      });
    } catch (error) {
      print(error);
    }
  }

  Future<void> _refresh() async {
    _total = 0;
    _residents = [];
    _params["pageNum"] = 1;
    await _getResidents();
  }
  
  // 添加公开刷新方法，供外部调用
  void refresh() {
    _refresh();
  }

  void _onScroll() {
    if (_isLoading || _total >= _residents.length) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _params["pageNum"] += 1;
        _getResidents();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getResidents();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FilterLayout(
      headerItems: [
        // FilterHeaderItem(title: "分组"),
        // FilterHeaderItem(title: "类别"),
        FilterHeaderItem(title: "状态"),
        FilterHeaderItem(
          title: "数量：$_total",
          render: (title) {
            return Text(
              title,
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
            );
          },
        ),
      ],
      dropdownItems: [
        // FilterDropdownItem(items: ["全部", "分组一"]),
        // FilterDropdownItem(items: ["全部", "整套", "合租", "整栋"]),
        FilterDropdownItem(
          items: _status,
          itemAsString: (item) => item["label"],
          compare: (item) => item["value"] == _params["status"],
          onChanged: (item) {
            setState(() {
              _params["status"] = item["value"];
            });
            _refresh();
          }
        ),
      ],
      child: RefreshIndicator(
        onRefresh: _refresh,
        child: _residents.isEmpty && !_isLoading
            ? SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                child: Container(
                  height: MediaQuery.of(context).size.height - 200, // 确保有足够高度支持下拉
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.people_outline,
                        size: 64,
                        color: ThemeVars.colorTextTer,
                      ),
                      const SizedBox(height: 16),
                      Text(
                        "暂无住户信息",
                        style: TextStyle(
                          fontSize: 16,
                          color: ThemeVars.colorTextTer,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            : ListView.separated(
                controller: _scrollController,
                padding: const EdgeInsets.all(ThemeVars.paddingPage),
                itemBuilder: (context, index) {
                  return GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      print("index:>>>>>>>>>>>$index");
                      Stacker.pushNamed(Keys.CHECK_IN_DETAIL, arguments: {"checkInId": _residents[index]["checkInId"]});
                      // Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                      //   return CheckInDetail(checkInId: _residents[index]["checkInId"]);
                      // }));
                    },
                    child: DecoratedBox(
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                        color: Colors.white,
                      ),
                      child: Stack(
                        children: [
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  _residents[index]["renterList"].length != 0 ? _residents[index]["renterList"][0]["name"] : "--",
                                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),),
                                const SizedBox(height: 6,),
                                Text("${_residents[index]["checkInStart"]} 至 ${_residents[index]["checkInEnd"]}", style: const TextStyle(fontSize: 13, color: ThemeVars.colorTextTer),),
                                const SizedBox(height: 2,),
                                Text("${_residents[index]["room"]["buildingName"]}${_residents[index]["room"]["name"]}"),
                              ],
                            ),
                          ),
                          if (_residents[index]["status"] == "2") Positioned(
                              right: 0,
                              top: 0,
                              child: Container(
                                width: 60,
                                height: 24,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(topRight: Radius.circular(8), bottomLeft: Radius.circular(15)),
                                  color: ThemeVars.colorBorder,
                                ),
                                child: const Text("已退房", style: TextStyle(fontSize: 12),),
                              )
                          ),
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (context, index) => const SizedBox(height: 8),
                itemCount: _residents.length,
              ),
      )
    );
  }
}
